/**
 * 直接更新 state 的多个方法的对象
 */

import Vue from 'vue'
import {
  RECEIVE_ADDRESS,
  RECEIVE_CATEGORYS,
  RECEIVE_SHOPS,
  RECEIVE_USER_INFO,
  RESET_USER_INFO,
  RECEIVE_GOODS,
  RECEIVE_INFO,
  RECEIVE_RATINGS,
  INCREMENT_FOOD_COUNT,
  DECREMENT_FOOD_COUNT,
  CLEAR_CART,
  RECEIVE_SEARCH_SHOPS,
  CLEAR_SEARCH_SHOPS,
} from './mutation-types'

export default {
  [RECEIVE_ADDRESS](state, {address}) {
    state.address = address
  },
  [RECEIVE_CATEGORYS](state, {categorys}) {
    state.categorys = categorys
  },
  [RECEIVE_SHOPS](state, {shops}) {
    state.shops = shops
  },
  [RECEIVE_USER_INFO](state, {userInfo}) {
    state.userInfo = userInfo
  },
  [RESET_USER_INFO](state) {
    state.userInfo = {}
  },
  
  [RECEIVE_GOODS](state, {goods}) {
    state.goods = goods
  },
  [RECEIVE_RATINGS](state, {ratings}) {
    state.ratings = ratings
  },
  [RECEIVE_INFO](state, {info}) {
    state.info = info
  },
  [INCREMENT_FOOD_COUNT](state, {food}) {
    if (!food.count) { // 第一次增加
      // food.count = 1 // 新增一个属性（这样写没有数据绑定效果）
      /**
       * 对象
       * 属性名
       * 属性值
       */
      Vue.set(food, 'count', 1)
      // 这样新增属性才能保证让新增的属性也有数据绑定效果
      // 将 food 添加到 cartFoods 中
      state.cartFoods.push(food)
    } else {
      food.count++
      // cartFoods 中的值也跟着改变
    }
  },
  [DECREMENT_FOOD_COUNT](state, {food}) {
    if (food.count) { // 有值才减少
      food.count--
      if (food.count === 0) {
        // 将 food 从 cartFoods 中移除
        // 寻找下标，删除一个
        state.cartFoods.splice(state.cartFoods.indexOf(food), 1)
      }
    }
  },

  // 清空购物车
  [CLEAR_CART](state) {
    // 清除 food 中的 count
    state.cartFoods.forEach(food => food.count = 0)
    // 移除购物车中所有购物项
    state.cartFoods = []
  },
  
  // 接收搜索的商家列表
  [RECEIVE_SEARCH_SHOPS](state, {searchShops}) {
    state.searchShops = searchShops
  },
}
